// pages/verify/verifydetail.js
var api = require('../../config/api.js');
var util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {

    //上报信息
    reportInfo: {
      //核实结果
      verifyResult:1,
      //情况说明
      verifySituation:'',
      //具体地址
      hiddenAddr:'',
      //防范措施
      suggestionMeasures:'',

      //提交数组
      fliePathImage: [],
      

    },

    imgList: [],


    //------oss上传所需参数------//
    ossAccessKeyId: '',
    policy: '',
    signature: '',
    //上传图片地址
    imagePathUrl: '',

  },

  //浏览图片
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },

  //浏览现场图片
  ViewImageed(e) {
    wx.previewImage({
      urls: this.data.imgListed,
      current: e.currentTarget.dataset.url
    });
  },

  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }

        //上传
        console.log(res.tempFilePaths[0])
        this.uploadfile(res.tempFilePaths[0])



      }
    });
  },

  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.data.reportInfo.fliePathImage.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList,
            ['reportInfo.fliePathImage']: this.data.reportInfo.fliePathImage
          })
        }
      }
    })
  },

  //----------上传文件--------------------//

  /**
     * 初始化参数
     */
  oss() {
    let that = this;
    //发起网络请求
    util.request(api.ossinit, null).then(function (res) {
      that.setData({
        policy: res.policy,
        ossAccessKeyId: res.ossAccessKeyId,
        signature: res.signature
      })
    }
    ).catch((err) => {
      console.log("远程服务器catch:" + err);
      //reject(err);
    });
  },

  /**
   * 上传文件
   */
  uploadfile(tempFilePath) {
    let that = this;
    const key = new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
    // 上传图片到oss
    wx.uploadFile({
      // 直传的oss地址
      url: 'https://hiddengwb.oss-cn-chengdu.aliyuncs.com',
      // 上传的文件
      filePath: tempFilePath,
      // 必须为file
      name: 'file',
      // 表单数据
      formData: {
        // key：文件路径，如 user/666.png
        //直接 key: "${filename}" 是存放在根目录，文件名为上传的文件名
        // 如果后端签名时指定了dir则开头必须同后端的一致，如后端指定了 “user/” 开头则必须是 user/xxx.xx
        'key': key,
        // 自定义成功响应值 ，默认响应204
        'success_action_status': '200',
        'OssAccessKeyId': this.data.ossAccessKeyId,
        // 后端签名后发回的policy
        'policy': this.data.policy,
        // 后端返回的签名
        'signature': this.data.signature
      },
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          console.log("上传成功！")

          var pathTemp = 'https://hiddengwb.oss-cn-chengdu.aliyuncs.com/' + key;
          that.data.reportInfo.fliePathImage.push(pathTemp);

        } else {
          console.log("上传失败！")
          console.log(res)
        }
      },
      fail(error) {
        console.log("上传错误")
        console.log(error)
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('row', function (data) {
      that.setData({
        reportInfo: data,
        ['reportInfo.verifyResult']:1,
        ['reportInfo.fliePathImage']:[],
        imgListed: data.fliePath.split(';')

      })

    })
    //获取oss上传参数
    this.oss();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  //-----------输入--------//
  bindverifySituation(event) {
    this.data.reportInfo.verifySituation = event.detail.value
    
  },
  bindhiddenAddr(event) {
    this.data.reportInfo.hiddenAddr = event.detail.value
    
  },
  bindsuggestionMeasures(event) {
    this.data.reportInfo.suggestionMeasures = event.detail.value
    
  },
  switchChange(event){
    if(event.detail.value){
      this.data.reportInfo.verifyResult=1
    }else{
      this.data.reportInfo.verifyResult=0
    }
  },

  //保存提交
  save() {
    if (this.data.reportInfo.verifySituation == '' || this.data.reportInfo.verifySituation == null) {
      util.showErrorToast('情况说明不能为空！');
      return false
    }
    if (this.data.reportInfo.suggestionMeasures == '' || this.data.reportInfo.suggestionMeasures == null) {
      util.showErrorToast('防范措施不能为空！');
      return false
    }
  
    //提交上报数据
    let dataup = this.data.reportInfo
    let that = this;
    console.log(JSON.stringify(dataup))
    that.loadModal();
    util.request(api.verifyHidden, JSON.stringify(dataup), 'POST').then(function (res) {
      console.log(res)
      if (res.code == '200') {
        that.closeModal();
        //刷新界面
        wx.navigateBack()

      } else {
        util.showErrorToast(res.message);
        that.closeModal();
      }

    }).catch((err) => {
      that.closeModal();
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });


  },





    //进度条
    loadModal() {
      this.setData({
        loadModal: true
      })
    },
    closeModal() {
      this.setData({
        loadModal: false
      })
    },





})